using EasyCaching.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using XjjXmm.Infrastructure.ToolKit;
using XjjXmm.Infrastructure.Cache;
using xjjxmm.infrastructure.ToolKit;

namespace XjjXmm.Infrastructure.User;

public class UserContext
{ 
	
    public string Id { get; set; } = string.Empty;

    public string ClientId { get; set; } = string.Empty;

    public string Token { get; set; } = string.Empty;

    public string LoginName { get; set; } = string.Empty;

    public string NickName { get; set; } = string.Empty;

    public string TenantId { get; set; } = string.Empty;
}


public interface IUserThreadContext
{
    public UserContext? UserContext { get; set; }
}

public class UserThreadContext : IUserThreadContext
{
    private static readonly AsyncLocal<UserContextHolder> asyncLocal = new AsyncLocal<UserContextHolder>();

    public UserThreadContext()
    {
        var a = "";
    }

    public void Set(UserContext value)
    {
        UserContext = value;
    }

    public UserContext? Get()
    {
        return UserContext;
    }

    public UserContext? UserContext
    {
        get => asyncLocal.Value?.Context;
        set
        {
            UserContextHolder? httpContextHolder = UserThreadContext.asyncLocal.Value;
            if (httpContextHolder != null)
                httpContextHolder.Context = null;
            if (value == null)
                return;

            asyncLocal.Value = new UserContextHolder()
            {
                Context = value
            };
        }
    }

    private sealed class UserContextHolder
    {
        public UserContext? Context;
    }
}